import { useEffect, useState } from 'react';
import { Link, useRequest, history } from 'umi';
import { useLocalStorageState, useSetState } from 'ahooks';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { TableDropdown } from '@ant-design/pro-table';

import {
  Table,
  Space,
  Card,
  Button,
  Form,
  Input,
  Select,
  PageHeader,
  Modal,
  Row,
  Col,
  Descriptions,
  Breadcrumb,
  TreeSelect,
  Image,
  Empty,
  Timeline,
  Tree,
  message,
} from 'antd';
import {
  MinusCircleOutlined,
  PlusOutlined,
  EditOutlined,
  CloseCircleOutlined,
  UserOutlined,
  BarChartOutlined,
  StockOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import zhCN from 'antd/lib/locale/zh_CN';
import moment from 'moment';
import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormDependency,
  ProFormTextArea,
} from '@ant-design/pro-components';
import ProCard from '@ant-design/pro-card';
// import { getValueByLabel } from '../getValueLable';
const { Option } = Select;

export default () => {
  const [gutter, setGutter] = useState(12);
  const [selectedTreeNode, setSelectedTreeNode] = useState<any>([]);
  const [addYearVisible, setAddYearVisible] = useState(false);
  const [editYearVisible, setEditYearVisible] = useState(false);
  const [rowRecord, setRowRecord] = useState({});
  const [debounceTime, setDebounceTime] = useState(10 * 1000);

  const [gender, setGender] = useState([]);
  const [countryType, seCountryType] = useState([]);
  const [country, setCountry] = useState([]);
  const [nation, setNation] = useState([]);
  const [politicalStatus, setPoliticalStatus] = useState([]);
  const [idType, setIdType] = useState([]);
  const [unit, setUnit] = useState([]);

  const userId = history.location.pathname.replace(
    '/SystemManage/StudentManagement/StudentInfo/',
    '',
  );

  const getCountryType = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'countryType', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(seCountryType(result));
      },
    },
  );
  const getCountry = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'country', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setCountry(result));
      },
    },
  );
  const getGender = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'gender', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setGender(result));
      },
    },
  );
  const getIdType = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'idType', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setIdType(result));
      },
    },
  );
  const getNation = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'nation', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setNation(result));
      },
    },
  );
  const getPoliticalStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'politicalStatus', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setPoliticalStatus(result));
      },
    },
  );
  const getUnit = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getLike',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { field: 'unit', ...data },
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(setUnit(result));
      },
    },
  );

  //管理员返回id对应用户的信息，用于表单
  const findOneStuUserInfoDetail = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/student/findOneStuUserInfoDetail',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //更新用户信息
  const updateStuUserById = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/student/updateStuUserById',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //添加用户
  const insertStuUser = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/student/insertStuUser',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //重置密码
  const reSetPassword = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/user/reSetPassword',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  return (
    <PageContainer
      header={{
        title: userId === 'new' ? '新建学生' : '编辑学生',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>系统管理</Breadcrumb.Item>
            <Breadcrumb.Item>学生管理</Breadcrumb.Item>
            <Breadcrumb.Item>
              {userId === 'new' ? '新建学生' : '编辑学生'}
            </Breadcrumb.Item>
          </Breadcrumb>
        ),
        extra: (
          <Button
            type="primary"
            onClick={() => {
              history.push('/SystemManage/StudentManagement');
            }}
          >
            返回学生管理
          </Button>
        ),
      }}
    >
      <ProCard
        title={
          <>
            {' '}
            <UserOutlined /> {' 基础信息'}
          </>
        }
        extra={
          userId != 'new' ? (
            <Button
              type="primary"
              icon={<ReloadOutlined />}
              loading={reSetPassword.loading}
              onClick={() => {
                reSetPassword.run({ id: userId }).then((data) => {
                  data
                    ? message.success('重置密码成功')
                    : message.error('重置密码失败');
                });
              }}
            >
              重置密码
            </Button>
          ) : (
            ''
          )
        }
      >
        <ProForm
          // layout="horizontal"
          grid
          request={async () => {
            var formData: any = {};
            if (userId != 'new') {
              await findOneStuUserInfoDetail
                .run({ id: userId })
                .then((data) => {
                  formData = data;
                });
            }
            return formData;
          }}
          onFinish={async (values) => {
            console.log(values);
            if (userId != 'new') {
              await updateStuUserById
                .run({
                  ...values,
                  groupType: 0,
                  year: parseInt(moment().format('YYYY')),
                })
                .then((data) => {
                  data
                    ? message.success('修改成功')
                    : message.error('修改失败');
                });
            } else {
              await insertStuUser
                .run({
                  ...values,
                  groupType: 0,
                  year: parseInt(moment().format('YYYY')),
                })
                .then((data) => {
                  data
                    ? message.success('添加成功')
                    : message.error('添加失败');
                });
            }
          }}
        >
          <ProFormText
            label="编号"
            name={'id'}
            colProps={{ span: 12 }}
            hidden
          />

          <ProForm.Group rowProps={{ gutter: gutter }}>
            <ProFormText
              label="用户名"
              name={'username'}
              colProps={{ span: 6 }}
              required
            />
            <ProFormText
              label="姓名"
              name={'realName'}
              colProps={{ span: 6 }}
              required
            />
          </ProForm.Group>

          <ProCard title="学籍信息" collapsible bordered headerBordered>
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormSelect.SearchSelect
                mode="single"
                label="学院"
                name={'unit'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                }}
                debounceTime={debounceTime}
                options={unit}
              />
              <ProFormText
                label={'导师姓名'}
                name={'teacherName'}
                colProps={{ span: 6 }}
                required
              />
              <ProFormDatePicker.Month
                label="进入实验室时间"
                name={'enterTime'}
                colProps={{ span: 6 }}
                required
              />
              <ProFormDatePicker.Month
                label="离开实验室时间"
                name={'exitTime'}
                colProps={{ span: 6 }}
                required
              />
            </ProForm.Group>
          </ProCard>
          <ProCard
            title="户籍信息"
            collapsible
            defaultCollapsed
            bordered
            style={{ marginTop: 6 }}
            headerBordered
          >
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormSelect
                label="性别"
                name={'gender'}
                colProps={{ span: 6 }}
                required
                debounceTime={debounceTime}
                fieldProps={{
                  labelInValue: false,
                }}
                options={gender}
              />
              <ProFormDatePicker
                label="出生日期"
                name={'birthday'}
                colProps={{ span: 6 }}
                required
              />
            </ProForm.Group>

            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormSelect
                label="国别"
                name={'countryType'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                  onChange: (e) => {
                    getCountry
                      .run({ field: 'country', level: e })
                      .then((data: any) => {
                        setCountry(data);
                      });
                  },
                }}
                options={countryType}
              />
              <ProFormSelect.SearchSelect
                mode="single"
                label="国家"
                name={'country'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                }}
                options={country}
              />
              <ProFormSelect.SearchSelect
                mode="single"
                label="民族"
                name={'nation'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                }}
                options={nation}
              />
              <ProFormSelect.SearchSelect
                mode="single"
                label="政治面貌"
                name={'politicalStatus'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                }}
                options={politicalStatus}
              />
            </ProForm.Group>
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormSelect
                label="证件类型"
                name={'idType'}
                colProps={{ span: 6 }}
                required
                fieldProps={{
                  labelInValue: false,
                }}
                options={idType}
              />
              <ProFormText
                label="证件号码"
                name={'idNumber'}
                colProps={{ span: 6 }}
                required
              />
            </ProForm.Group>
          </ProCard>
          <ProCard
            title="账号信息"
            collapsible
            defaultCollapsed
            bordered
            style={{ marginTop: 6 }}
            headerBordered
          >
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormSelect
                label="用户状态"
                name={'status'}
                colProps={{ span: 6 }}
                options={[
                  { label: '正常', value: 1 },
                  { label: '停用', value: 0 },
                ]}
                required
              />
              <ProFormSelect
                mode={'multiple'}
                name={'roles'}
                label={'用户权限'}
                required
                colProps={{ span: 6 }}
                options={[{ label: '学生', value: 5 }]}
              />
            </ProForm.Group>
          </ProCard>
          <ProCard
            title="联系方式"
            collapsible
            defaultCollapsed
            bordered
            style={{ marginTop: 6, marginBottom: 12 }}
            headerBordered
          >
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormText
                label="固定电话号码"
                name={'phoneNum'}
                colProps={{ span: 9 }}
                required
              />
              <ProFormText
                label="手机号码"
                name={'mobilePhoneNum'}
                colProps={{ span: 9 }}
                required
              />
            </ProForm.Group>
            <ProForm.Group rowProps={{ gutter: gutter }}>
              <ProFormText
                label="电子邮箱"
                name={'email'}
                colProps={{ span: 9 }}
                required
              />
              <ProFormText
                label="传真"
                name={'faxNum'}
                colProps={{ span: 9 }}
                required
              />
            </ProForm.Group>
          </ProCard>
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};
